package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    //本地缓存(java进程缓存,在一个jvm里):单体应用推荐
    //分布式部署多实例时:本地缓存的数据在各实例之间不共享,如果缓存有更新,各实例之间的缓存数据可能不一致
    private Map<String, Object> cache = new HashMap<>();

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> queryTreeList(Map<String, Object> params) {
        List<CategoryEntity> categoryEntityList = this.baseMapper.selectList(null);
        List<CategoryEntity> rootList = categoryEntityList.stream().filter(item -> item.getParentCid() == 0).sorted(this.getComparator()).collect(Collectors.toList());
        return this.recursiveTreeList(rootList, categoryEntityList);
    }

    @Override
    public void removeBatchIds(List<Long> asList) {
        //todo 判断节点是否被引用
        this.baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        findParentPath(catelogId, paths);
        Collections.reverse(paths);
        return paths.toArray(new Long[paths.size()]);
    }

    /**
     * 级联更新关联数据
     *
     * @CacheEvict 失效模式
     *
     *
     * category::getLevel1CategoryList 作为key 在redis可视化界面会以树形结构展示，类似分组
     * @param category
     */
    // @CacheEvict(value = "category", key = "'getLevel1CategoryList'") // 删除一个缓存
    // @Caching(evict = {
    //         @CacheEvict(value = "category", key = "'getLevel1CategoryList'"),
    //         @CacheEvict(value = "category", key = "'getCatalogjson4'")
    // }) //删除多个缓存
    @CacheEvict(value = "category", allEntries = true) //删除这个分区下的所有key的缓存
    @Transactional
    @Override
    public void updateDetailById(CategoryEntity category) {
        this.updateById(category);
        if (StringUtils.isNotBlank(category.getName())) {
            this.categoryBrandRelationService.updateCategoryName(category.getCatId(), category.getName());
        }
    }

    @Cacheable(value = "category", key = "#root.methodName")
    @Override
    public List<CategoryEntity> getLevel1CategoryList() {
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }

    //key 接收的是spel表达式，字符串时用单引号包裹
    // @Cacheable(value = {"category"}, key = "'Level1Category'")
    @Cacheable(value = {"category"}, key = "#root.method.name")
    @Override
    public List<CategoryEntity> getLevel1CategoryListForDemo() {
        System.out.println("getLevel1CategoryListForDemo............");
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }

    /**
     * 借助redis实现分布式锁
     * @return
     */
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogjson() {
        return getCatalogjson3();
    }

    /**
     * 从缓存获取数据或者从db获取数据并缓存到redis
     * @return
     */
    private Map<String, List<Catelog2Vo>> getCatalogjsonData() {
        //拿到分布式锁后也先从缓存查一次
        String catalogJSON = redisTemplate.opsForValue().get("catalogJson");
        if (StringUtils.isEmpty(catalogJSON)) {
            Map<String, List<Catelog2Vo>> result = getCatalogjsonFromDB();
            String jsonString = JSON.toJSONString(result);
            //将db数据向redis存一份
            redisTemplate.opsForValue().set("catalogJson", jsonString, 1, TimeUnit.HOURS);
            return result;
        }

        System.out.println(" ================ 缓存命中2 ================ ");

        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {});
        return result;
    }


    @Override
    public Map<String, List<Catelog2Vo>> getCatalogjson1() {
        //从redis读取
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        Map<String, List<Catelog2Vo>> catalogjsonFromDbOrRedis;
        if (StringUtils.isEmpty(catalogJson)) {
            //查db
            catalogjsonFromDbOrRedis = getCatalogjsonFromLocalLock();
        } else {
            //查redis
            System.out.println(" ================ 缓存命中1 ================ ");
            catalogjsonFromDbOrRedis = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {});
        }
        return catalogjsonFromDbOrRedis;
    }

    @Override
    public Map<String, List<Catelog2Vo>> getCatalogjson2() {
        //从redis读取
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        Map<String, List<Catelog2Vo>> catalogjsonFromDbOrRedis;
        if (StringUtils.isEmpty(catalogJson)) {
            //查db
            catalogjsonFromDbOrRedis = getCatalogjsonFromRedisLock();
        } else {
            //查redis
            System.out.println(" ================ 缓存命中1 ================ ");
            catalogjsonFromDbOrRedis = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {});
        }
        return catalogjsonFromDbOrRedis;
    }

    @Override
    public Map<String, List<Catelog2Vo>> getCatalogjson3() {
        //从redis读取
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        Map<String, List<Catelog2Vo>> catalogjsonFromDbOrRedis;
        if (StringUtils.isEmpty(catalogJson)) {
            //查db
            catalogjsonFromDbOrRedis = getCatalogjsonFromRedissonLock();
        } else {
            //查redis
            System.out.println(" ================ 缓存命中1 ================ ");
            catalogjsonFromDbOrRedis = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {});
        }
        return catalogjsonFromDbOrRedis;
    }


    @Cacheable(value = "category", key = "#root.methodName")
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogjson4() {
        //一级分类数据
        List<CategoryEntity> level1CategoryList = this.getLevel1CategoryList();
        Map<String, List<Catelog2Vo>> map = level1CategoryList.stream().collect(Collectors.toMap(k1 -> k1.getCatId().toString(), v1 -> {
            //二级分类数据
            List<CategoryEntity> level2CategoryList = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v1.getCatId()));

            List<Catelog2Vo> catelog2Vos = level2CategoryList.stream().map(v2 -> {
                //三级分类数据
                List<CategoryEntity> level3CategoryList = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v2.getCatId()));

                List<Catelog2Vo.Catelog3Vo> catelog3VoList = level3CategoryList.stream().map(v3 -> {
                    Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(v2.getCatId().toString(), v3.getCatId().toString(), v3.getName());
                    return catelog3Vo;
                }).collect(Collectors.toList());

                Catelog2Vo catelog2Vo = new Catelog2Vo(v1.getCatId().toString(), catelog3VoList, v2.getCatId().toString(), v2.getName());

                return catelog2Vo;
            }).collect(Collectors.toList());

            return catelog2Vos;
        }));

        System.out.println(" ================ 缓存不命中,查询了数据库 ================ ");

        return map;
    }

    private Map<String, List<Catelog2Vo>> getCatalogjsonFromRedissonLock() {
        //使用redisson获取分布式锁
        RLock lock = redissonClient.getLock("my-lock");
        //加锁，30秒后自动解锁
        lock.lock(30, TimeUnit.SECONDS);

        Map<String, List<Catelog2Vo>> result;
        try {
            result = getCatalogjsonData();
        } finally {
            lock.unlock();
        }

        return result;
    }

    private Map<String, List<Catelog2Vo>> getCatalogjsonFromRedisLock() {
        String uuid = UUID.randomUUID().toString();
        //加锁    这里过期时间设置为300秒,防止锁在删除前提前过期;(锁续期 TODO)
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        //lock 为true 加锁成功
        if (lock) {
            Map<String, List<Catelog2Vo>> result;
            try {
                result = getCatalogjsonData();
            } finally {
                //lua解锁脚本
                String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                        "then\n" +
                        "    return redis.call(\"del\",KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end\n";
                //解锁
                Long execute = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);
            }
            return result;
        } else {
            //获取锁失败
            System.out.println("获取分布式锁失败..... 等待重试");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatalogjsonFromRedisLock();//自旋的方式尝试获取锁
        }
    }

    /**
     * 本地锁:这里用的是同步代码块
     * 也可使用 synchronized 修饰成同步方法
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogjsonFromLocalLock (){
        //        本地缓存
/*        Map<String, List<Catelog2Vo>> catalogJson = (Map<String, List<Catelog2Vo>>)cache.get("catalogJson");
        if (null == catalogJson) {
            Map<String, List<Catelog2Vo>> catalogjsonFromDB = getCatalogjsonFromDB();
            cache.put("catalogJson", catalogjsonFromDB);
        }
        return catalogJson;*/

        // redis缓存
        /*
         * 高并发下缓存失效问题: 缓存失效,请求都转到db,db瞬间压力过大,挂掉
         * 缓存穿透:查询一个不存在的数据,缓存和db都不存在
         * 解决:从缓存中查到的null结果存入缓存,并设置短暂的过期时间
         *
         * 缓存雪崩:缓存的key大面积失效
         * 解决:给key的失效时间设置一个随机值
         *
         * 缓存击穿:缓存中一个热点数据设置了过期时间,但是在高频访问前失效了.
         *        缓存中本来存在该数据,但是过期了.db中有
         *
         * 特别注意缓存穿透和缓存击穿的区别-
         * */

        //springboot容器中注册的bean默认都是单例的
        //只要是同一把锁,就能锁住这个锁的所有线程
        //查询db和向redis写入缓存放在同一把锁内
        synchronized (this) {
            //得到锁后，先从缓存中确定下是否存在，不存在的才去查db
            String catalogJson = redisTemplate.opsForValue().get("catalogJson");
            if (StringUtils.isEmpty(catalogJson)) {
                //此处查db然后向redis写数据可以用 getCatalogjsonData() 返回
                Map<String, List<Catelog2Vo>> catalogjsonFromDB = getCatalogjsonFromDB();
                String jsonString = JSON.toJSONString(catalogjsonFromDB);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                redisTemplate.opsForValue().set("catalogJson", jsonString, 1, TimeUnit.HOURS);
                return catalogjsonFromDB;
            }

            //复杂类型用 TypeReference, TypeReference的构造函数是受保护的(protected),这个new一个匿名内部类来创建
            Map<String, List<Catelog2Vo>> parseObject = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {});

            System.out.println(" ================ 缓存命中2 ================ ");

            return parseObject;
        }
    }

    /**
     * 从db获取数据
     * @return
     */
    //从数据库中查询并封装三级分类数据
    public Map<String, List<Catelog2Vo>> getCatalogjsonFromDB() {
        //一级分类数据
        List<CategoryEntity> level1CategoryList = this.getLevel1CategoryList();
        Map<String, List<Catelog2Vo>> map = level1CategoryList.stream().collect(Collectors.toMap(k1 -> k1.getCatId().toString(), v1 -> {
            //二级分类数据
            List<CategoryEntity> level2CategoryList = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v1.getCatId()));

            List<Catelog2Vo> catelog2Vos = level2CategoryList.stream().map(v2 -> {
                //三级分类数据
                List<CategoryEntity> level3CategoryList = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v2.getCatId()));

                List<Catelog2Vo.Catelog3Vo> catelog3VoList = level3CategoryList.stream().map(v3 -> {
                    Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(v2.getCatId().toString(), v3.getCatId().toString(), v3.getName());
                    return catelog3Vo;
                }).collect(Collectors.toList());

                Catelog2Vo catelog2Vo = new Catelog2Vo(v1.getCatId().toString(), catelog3VoList, v2.getCatId().toString(), v2.getName());

                return catelog2Vo;
            }).collect(Collectors.toList());

            return catelog2Vos;
        }));

        System.out.println(" ================ 缓存不命中,查询了数据库 ================ ");

        return map;
    }

    private void findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity entity = this.getById(catelogId);
        if (entity.getParentCid() != 0) {
            findParentPath(entity.getParentCid(), paths);
        }
    }

    private List<CategoryEntity> recursiveTreeList(List<CategoryEntity> currentList, List<CategoryEntity> sourceList) {
        currentList.stream().forEach(r -> {
            r.setLabel(r.getName());
            if (this.hasChildList(r, sourceList)) {
                List<CategoryEntity> childList = this.getChildList(r, sourceList);
                r.setChildren(childList);
                this.recursiveTreeList(childList, sourceList);
            }
        });
        return currentList;
    }

    private List<CategoryEntity> getChildList(CategoryEntity current, List<CategoryEntity> sourceList) {
        return sourceList.stream().filter(item -> item.getParentCid().equals(current.getCatId())).sorted(this.getComparator()).collect(Collectors.toList());
    }
    
    private boolean hasChildList(CategoryEntity current, List<CategoryEntity> sourceList) {
        return !CollectionUtils.isEmpty(this.getChildList(current, sourceList));
    }

    /**
     * 也可以在查询时通过数据库字段来排序: mysql默认升序，null在最前
     * Comparator.nullsFirst 排序字段值为空时放在最前面
     * @return
     */
    private Comparator<CategoryEntity> getComparator() {
        // 默认升序
        return Comparator.comparing(CategoryEntity::getSort, Comparator.nullsFirst(Integer::compareTo));
        // 降序
        // return Comparator.comparing(CategoryEntity::getSort, Comparator.nullsFirst(Integer::compareTo)).reversed();
    }

}